package com.wzqj.agent.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.stat.TableStat.Mode;
import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.common.Log;
import com.wzqj.agent.common.Page;
import com.wzqj.agent.common.constant.WebConstant;
import com.wzqj.agent.util.ValidateUtil;
import com.wzqj.agent.web.domain.Agent;
import com.wzqj.agent.web.domain.Detail;
import com.wzqj.agent.web.domain.User;
import com.wzqj.agent.web.service.AgentService;
import com.wzqj.agent.web.service.DetailService;
import com.wzqj.agent.web.service.UserService;
import com.wzqj.web.http.CookieUtils;
import com.wzqj.wsp.config.Config;
import com.wzqj.wsp.http.HttpUtil;

@Controller
@RequestMapping("/agent")
public class AgentWebController {
	private Logger log = LogManager.getLogger(AgentWebController.class);

	@Autowired
	private AgentService agentService;
	@Autowired
	private UserService userService;
	@Autowired
	private DetailService detailService;
	
	/**
	 * 查询代理商(根据用户中的角色id)
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/agentList")
	public String agentList(@RequestParam(value = "pageNo", defaultValue = "1")  Integer pageNo,
			ModelMap map,HttpSession session,HttpServletRequest request){
		String rv = "";
		try {
			Config.getConstants().setUserToken(WebConstant.userToken_key);
			String userToken = CookieUtils.findACookieToken(request);
			Log.run.error("userToken:" + userToken);
			if (userToken==null||userToken.equals("")) {
				//return "redirect:user/index.xhtml";
				return "/user/admin/login";
			}
			Integer userId = Integer.parseInt(userToken);
	        
			//获取用户信息
			User user  = userService.getById(userId);
			request.setAttribute("user", user);
			//获取用户 下的代理商信息
			Page<Agent> agentsPage = agentService.getByUserPage(userId,pageNo); 
			request.setAttribute("pageNo", pageNo);
			
			if(agentsPage!=null){
				log.info("agents："+agentsPage);
				request.setAttribute("agents", agentsPage);
				
			}
			//判断即将跳转的页面
			Integer roleId = user.getRoleId();
			if (WebConstant.roleID_admin==roleId) {//超级管理员
				rv="/user/agent/agentManagement";
			}else if(WebConstant.roleID_agent_level1==roleId){//一级代理商
				Agent agentSelf = agentService.getById(user.getTypeId());
				if (WebConstant.agent_proxy_yes == agentSelf.getProxy()) {//有代理权，可以代理商管理和业务员管理
					rv="/user/agent/agentManagement";
				}
				if (WebConstant.agent_proxy_no == agentSelf.getProxy()) {//无代理权，只能业务员管理
					rv="redirect:/sales/salesList.xhtml";
				}
				request.setAttribute("agentSelf", agentSelf);
			}else if(WebConstant.roleID_agent_level2==roleId){//二级代理商
				rv="redirect:/sales/salesList.xhtml";
			}
			
			
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return rv;
	};
	
	@RequestMapping("/toInsert")
	public String toInsert(HttpServletRequest request ,ModelMap map){
		Config.getConstants().setUserToken(WebConstant.userToken_key);
		String userToken = CookieUtils.findACookieToken(request);
		Log.run.error("userToken:" + userToken);
		if (userToken==null||userToken.equals("")) {
			return "redirect:user/index.xhtml";
		}
		Integer userId = Integer.parseInt(userToken);
		User user = userService.getById(userId);
		map.put("user", user);
		return "/user/agent/agentAdd";
	}
	
	/**
	 * 新增代理商
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/insert")
	@ResponseBody
	public JSONObject insert(Integer parentId,String name,Integer level,String authorZone,String contactPhone,
			String contactName,Integer proxy,Integer roleId,
			ModelMap map,HttpSession session,HttpServletRequest request){
		JSONObject data = new JSONObject();
		try {
			
			//如果该代理商已存在
			User isExit = userService.getByUsername(contactPhone);
			if (isExit!=null) {
				data.put("status", 0);
				data.put("info", "该手机号已存在！");
				return data;
			}
			//新建代理商
			Agent agent = new Agent();
			agent.setName(name);
			if (level!=null&&level!=0) {
				
				agent.setLevel(level);
			}
			agent.setAuthorZone(authorZone);
			if (proxy!=null&&proxy!=0) {
				
				agent.setProxy(proxy);
			}
			agent.setContactName(contactName);
			agent.setParentId(parentId);
			agent.setStatus(1);
			if (!ValidateUtil.isMobile(contactPhone)) {
				data.put("status", 0);
				data.put("info", "该代理商手机号格式不正确！");
				return data;
			}
			agent.setContactPhone(contactPhone);
			agentService.insert(agent);
			
			
			//新建用户信息
			//新建用户
			User user = new User();
			user.setUsername(agent.getContactPhone());
			user.setPassword(agent.getContactPhone());//默认密码为注册手机号
			
			user.setRoleId(roleId);//1:一级代理商    2：二级代理商
			user.setStatus(WebConstant.status_normal);//正常状态
			user.setType(WebConstant.user_type_agent);//0：admin 1:代理商（包括一级和二级）3：业务员
			Agent ag = agentService.getByContactPhone(agent.getContactPhone());
			user.setTypeId(ag.getId());//标识用户账号所属的代理商
			userService.insert(user);
			
			Detail detail = new Detail();
			detail.setAgentId(ag.getId());
			detail.setAgentPhone(agent.getContactPhone());
			detail.setOperation(WebConstant.add_agent_operation);
			detail.setStatus(WebConstant.status_success);
			detailService.insert(detail);
			
			data.put("status", 1);
			data.put("info", "新建代理商成功！");
			data.put("data", agent);
			
		} catch (Exception e) {
			data.put("status",0);
			data.put("info", "新建代理商失败！");
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return data;
	}
	/**
	 * 跳转到代理商修改页面
	 * @param map
	 * @param agentId
	 * @return
	 */
	@RequestMapping("/toEdit")
	public String toEdit(ModelMap map,Integer agentId,HttpServletRequest request){
		Config.getConstants().setUserToken(WebConstant.userToken_key);
		String userToken = CookieUtils.findACookieToken(request);
		Log.run.error("userToken:" + userToken);
		if (userToken==null||userToken.equals("")) {
			return "redirect:user/index.xhtml";
		}
		Integer userId = Integer.parseInt(userToken);
		User user = userService.getById(userId);
		map.put("user", user);
		Agent agent = agentService.getById(agentId);
		map.addAttribute("agent", agent);
		return "/user/agent/agentEdit";
	}
	/**
	 * 修改代理商
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public JSONObject edit(Integer agentId,String name,Integer level,String authorZone,String province,String city,String contactPhone,
			String contactName,Integer proxy,
			ModelMap map,HttpSession session,HttpServletRequest request){
		JSONObject data = new JSONObject();
		try {
			
			//修改代理商
			Agent agent = agentService.getById(agentId);
			if (!StringUtils.isEmpty(name)) {
				agent.setName(name);
			}
			if (!StringUtils.isEmpty(contactName)) {
				agent.setContactName(contactName);
			}
			if (!StringUtils.isEmpty(contactPhone)) {
				agent.setContactPhone(contactPhone);
			}
			if (!StringUtils.isEmpty(authorZone)) {
				agent.setAuthorZone(authorZone);
			}
			if (!StringUtils.isEmpty(province)) {
				agent.setProvince(province);
			}
			if (!StringUtils.isEmpty(city)) {
				agent.setCity(city);
			}
			if (level!=null) {
				
				agent.setLevel(level);
			}
			if (proxy!=null) {
				
				agent.setProxy(proxy);
			}
			
			agentService.update(agent);
			data.put("status", 1);
			data.put("info", "修改代理商成功！");
			data.put("data", agent);
		} catch (Exception e) {
			data.put("status",0);
			data.put("info", "修改代理商失败！");
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return data;
	}
	/**
	 * 冻结/解冻代理商的账户
	 * @param agentId
	 * @param userStatus
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/freeze")
	public JSONObject freeze(Integer type,Integer agentId,Integer status,
			ModelMap map,HttpServletRequest request ){
		JSONObject data = new JSONObject();
		try {//冻结/解冻用户
			User user = userService.getByType(type, agentId);
			user.setStatus(status);//冻结/解冻
			userService.update(user);
			
			//冻结/解冻代理商
			Agent agent =  agentService.getById(user.getTypeId());
			agent.setStatus(status);//冻结/解冻
			agentService.update(agent);
			
			data.put("status", 1);
	
			if (status==0) {
				data.put("info", "冻结成功！");
			}
			if (status==1) {
				data.put("info", "解冻成功！");
			}
			
		} catch (Exception e) {
			data.put("status",0);
			if (status==0) {
				data.put("info", "冻结失败！");
			}
			if (status==1) {
				data.put("info", "解冻失败！");
			}
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return data;
	}
	
	/**
	 * 获取省市区三级联动信息
	 * @param prov
	 * @param request
	 * @return
	 */
	@RequestMapping("/authorZone")
	@ResponseBody
	public JSONObject authorZone(String key,String value,String url,HttpServletRequest request,ModelMap map,HttpSession session){
		JSONObject params = new JSONObject();
		params.put(key, value);
		String result = HttpUtil.getResult(url, params, true);
		JSONObject data = JSONObject.parseObject(result);
		return data;
	};
	
}


	
	